<template>
  <div class="avatar-uploader">
    <el-upload
      v-if="isImg"
      :action="actionUrl"
      show-file-list
      list-type="picture-card"
      :limit="5"
      :file-list="fileList"
      :headers="headers()"
      :on-preview="downLoadFile"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus avatar-uploader-icon"></i>
      <div class="el-upload__tip" slot="tip">
        只能上传jpg/png文件，且不超过{{ maxSize }}
      </div>
    </el-upload>
    <template v-else>
      <el-upload
        v-if="limit === -1"
        drag
        :action="actionUrl"
        :file-list="fileList"
        multiple
        :headers="headers()"
        :on-preview="downLoadFile"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <el-upload
        v-else
        drag
        :action="actionUrl"
        :file-list="fileList"
        multiple
        :limit="limit"
        :headers="headers()"
        :on-preview="downLoadFile"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </template>
  </div>
</template>

<script>
import {
  equals,
  isFalse,
  isListEmpty,
  isNotNull,
  listRemove,
  msgError,
  msgSuccess,
  notEquals,
} from "@/util/common-util";
import { getToken } from "@/util/auth";
import { downFile, removeImg } from "@/api/business/attachment-file";

// fileList
// {
//   attachId: '1558391842446143490',
//     url: "http://47.99.146.68:9000/stkj/upload/20220813/fa5be3da03a475efb74ff763824374cf.jpeg"
// }]

export default {
  name: "app-file-upload",
  props: {
    isImg: {
      type: Boolean,
      default: true,
    },
    maxSize: {
      type: String,
      default: "500Kb", // 500Kb 1Mb 5Mb
    },
    limit: {
      type: Number,
      default: -1,
    },
    initImgs: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      attachIds: [],
      fileList: [],
      removeFileList: [],
      actionUrl:
        "http://47.96.180.150:8080/admin-resource/oss/endpoint/put-file-by-name",
      // actionUrl: "/admin/oss/endpoint/put-file-attachment",
    };
  },
  created() {
    this.init(this.initImgs);
  },
  methods: {
    init(initImgs) {
      if (isListEmpty(initImgs)) return;
      this.fileList = [];
      for (const item of initImgs) {
        this.fileList.push({
          attachId: item.id,
          url: item.link,
          name: item.name,
        });
      }
    },
    headers() {
      return { "Uic-Auth": "bearer " + getToken() };
    },
    handleSuccess(res, file) {
      this.fileList.push(file);
      this.doOutput();
    },
    handleRemove(file) {
      // 从list中删除
      let index = -1;
      const attachId = isNotNull(file.attachId)
        ? file.attachId
        : file.response.data.attachId;
      for (let i = 0; i < this.fileList.length; i++) {
        if (isNotNull(this.fileList[i].attachId)) {
          if (equals(this.fileList[i].attachId, attachId)) {
            index = i;
            break;
          }
        } else {
          if (equals(file.response.data.attachId, attachId)) {
            index = i;
            break;
          }
        }
      }
      if (index !== -1) {
        listRemove(this.fileList, index);
        this.removeFileList.push(file);
        this.doOutput();
      }
    },
    doRemove(file) {
      const attachId = isNotNull(file.attachId)
        ? file.attachId
        : file.response.data.attachId;
      removeImg(attachId).then((res) => {});
    },
    removeFile() {
      for (const item of this.removeFileList) {
        this.doRemove(item);
      }
    },
    doOutput() {
      const re = [];
      this.fileList.forEach((f) => {
        if (isNotNull(f.attachId)) {
          re.push(f.attachId);
        } else {
          re.push(f.response.data.attachId);
        }
      });
      this.$emit("change", re);
    },
    beforeUpload(file) {
      if (isFalse(this.isImg)) return;
      if (
        notEquals(file.type, "image/jpeg") &&
        notEquals(file.type, "image/png")
      ) {
        msgError("上传头像图片只能是 jpg/png 格式!");
        return false;
      }
      if (equals(this.maxSize, "500Kb") && file.size / 1024 > 500) {
        msgError("上传头像图片大小不能超过 500Kb!");
        return false;
      }
      if (equals(this.maxSize, "1Mb") && file.size / 1024 / 1024 > 1) {
        msgError("上传头像图片大小不能超过 1MB!");
        return false;
      }
      if (equals(this.maxSize, "5Mb") && file.size / 1024 / 1024 > 5) {
        msgError("上传头像图片大小不能超过 5MB!");
        return false;
      }
      return true;
    },
    downLoadFile(file) {
      let downloadElement = document.createElement("a");
      downloadElement.href = file.url;
      // 下载后文件名
      downloadElement.download = file.name;
      document.body.appendChild(downloadElement);
      // 点击下载
      downloadElement.click();
      // 下载完成移除元素
      document.body.removeChild(downloadElement);
      // 释放掉blob对象
      window.URL.revokeObjectURL(href);
    },
  },
};
</script>

<style lang="scss">
.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  ::v-deep .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 130px;
    height: 130px;
    line-height: 130px;
    text-align: center;
  }

  .avatar {
    width: 130px;
    height: 130px;
    display: block;
  }
}
</style>
